import fastifyJwt, { FastifyJwtNamespace } from '@fastify/jwt';
import fp from 'fastify-plugin';
import { CustomError, ERROR_CODE } from './err';

export const WHITE_URL = /^\/(auth|static)\//i;

declare module "@fastify/jwt" {
    interface FastifyJWT {
        payload: { id: number | string, email: string }
        user: {
            id: number | string,
            email: string,
        }
    }
}

export default fp(function (fastify, opts, done) {
    fastify.register(fastifyJwt, {
        secret: 'supersecret',
        cookie: {
            cookieName: 'token',
            signed: false
        }
    });

    fastify.addHook("onRequest", async (request, reply) => {
        if (WHITE_URL.test(request.url) || request.method === 'OPTIONS') {
            return;
        }

        try {
            await request.jwtVerify()
        } catch (err) {
            throw new CustomError((err as any)?.message || '', ERROR_CODE.NO_AUTHORIZATION);
        }
    });

    done();
});